<?php
/*
 * Post a rating.
 */

// authenticate user first
F3::call('authentication.php');
if (F3::exists('auth_error'))
{
  	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "User is not authenticated.");
	echo json_encode($err);
	return;
}

if (!F3::exists('POST.recipe_id') || !F3::exists('POST.rating')):
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "Rating and recipe id are required.");
	echo json_encode($err);
	return;
endif;

// get user ID from session
$id = F3::get('SESSION.user_id');

// does recipe exist?
$rid = F3::get('POST.recipe_id');
$param = array('1'=>$rid);
$result = DB::sql("SELECT rid from recipes where rid = ?", $param);
if(count($result)==0):
	//the recipe doesn't exist
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "Recipe does not exist.");
	echo json_encode($err);
	return;
endif;

// does exact comment already exist?
$rating = F3::get('POST.rating');
$param = array('1'=>$rid, '2'=>$id);
$result = DB::sql("SELECT rating from ratings where rid = ? and uid = ?", $param);
if(count($result)>0):
	// rating exists, update
	$param = array('1'=>$rating,'2'=>$rid, '3'=>$id);
	DB::sql("UPDATE ratings set rating = ? where rid = ? and uid = ?", $param);

else:
	// add new rating
	$param = array('1'=>$rid,'2'=>$id, '3'=>$rating);
	DB::sql("insert into ratings (rid, uid, rating) values(?,?,?)", $param);
endif;

// success
header('HTTP/1.1 204');
header("Content-Type: application/json");
$response = "Comment added.";
echo json_encode($response);
return;
?>
